package hb;

import java.util.Iterator;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

import zhuzhuwang.HibernateSessionFactory;

public class UserDao {
	private SessionFactory sessions=null;
	private Session mySession=null;
	private Transaction tx;
	
	public UserDao(){
		sessions=new Configuration().configure().buildSessionFactory();
	}
	
	public int verifyUser(String userName,String password){
		int flag=0;
		
		mySession=sessions.openSession();		
		String hql="from User u where u.userName =:uN";
		Query query=mySession.createQuery(hql);
		query.setParameter("uN", userName);
		
		List list=query.list();
		Iterator it=list.iterator();
		if(it.hasNext()){
			User user=(User)it.next();
			if(user.getPassword().equals(password)){
				if(user.getAdmin().equals(1))
					flag=9;
				else
					flag=0;
			}
			else{
				flag=1;
			}
		}
		else{
			flag=2;
		}
		
		mySession.close();
		
		return flag;
	}
	
	public void insert(User user){
		
		mySession=sessions.openSession();	
		tx=mySession.beginTransaction();		
		try{
			mySession.save(user);
			tx.commit();
		}catch(Exception ex){
	//		ex.printStackTrace();
		}finally{
			mySession.close();
		}
		
	}
	
	public User getUser(String userName){
		User u=new User();
		
		mySession=sessions.openSession();

		String hql="from User u where u.userName =:uN";
		Query query=mySession.createQuery(hql);
		query.setParameter("uN", userName);
		
		List list=query.list();
		Iterator it=list.iterator();
		if(it.hasNext())
		{
			u=(User) it.next();
		}

		mySession.close();
		
		return u;
	}
	
	public User getUserByID(String id){
		User u=new User();
		
		mySession=sessions.openSession();

		String hql="from User u where u.userId =:uN";
		Query query=mySession.createQuery(hql);
		query.setParameter("uN", Integer.parseInt(id));
		
		List list=query.list();
		Iterator it=list.iterator();
		if(it.hasNext())
		{
			u=(User) it.next();
		}

		mySession.close();
		
		return u;
	}
	
	public void update(User user){
		mySession=sessions.openSession();
		tx=mySession.beginTransaction();
		mySession.update(user);
		tx.commit();
		mySession.close();
	}
	
	public void delete(User user){
		mySession=sessions.openSession();
		tx=mySession.beginTransaction();
		mySession.delete(user);
		tx.commit();
		mySession.close();
	}
}
